package danran.dbapi.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import danran.dbapi.common.ApiConfig;
import danran.dbapi.domain.ApiDto;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * @Classname ApiConfigMapper
 * @Description TODO
 * @Date 2022/1/12 22:31
 * @Created by RanCoder
 */
@Mapper
public interface ApiConfigMapper extends BaseMapper<ApiConfig> {
    /***
     * 根据path去查询上线了的api
     * @param path API path
     * @return API config
     */
    @Select("select * from api_config where path=#{path} and status = 1")
    ApiConfig selectByPathOnline(String path);

    /***
     * 根据关键字查询api
     * @param keyword
     * @param field
     * @param groupId
     * @return
     */
    @Select("<script>" +
            "select * from api_config\n" +
            "<where>\n" +
            "<if test='groupId != null and groupId !=\"\"'> group_id = #{groupId} </if>\n" +
            "<if test='keyword != null and keyword !=\"\"'>\n" +
            "\t<if test='field != null and field !=\"\"'> and ${field} like #{keyword} </if>\n" +
            "\t<if test='field == null or field ==\"\"'> and (name like #{keyword} or note like #{keyword} or path like #{keyword} )</if>\n" +
            "</if>\n" +
            "</where>" +
            "</script>")
    List<ApiConfig> selectByKeyword(@Param("keyword") String keyword,
                                    @Param("field") String field,
                                    @Param("groupId") String groupId);

    /***
     * 统计某个path的api的个数
     * @param path
     * @return
     */
    @Select("select count(1) from api_config where path=#{path}")
    Integer selectCountByPath(String path);

    /***
     * 统计已经更新的api
     * @param path
     * @param id
     * @return
     */
    @Select("select count(1) from api_config where path=#{path} and id != #{id}")
    Integer selectCountByPathWhenUpdate(@Param("path") String path, @Param("id") String id);

    /***
     *
     * @param id
     * @return
     */
    @Select("select count(1) from api_config where datasource_id = #{id}")
    int countByDatasoure(String id);

    /***
     *
     * @param id
     * @return
     */
    @Select("select count(1) from api_config where group_id = #{id}")
    int selectCountByGroup(String id);

    /***
     *
     * @return
     */
    @Results(id = "accResultMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "group_name", column = "groupName")
    })
    @Select("select t1.id,t1.name,t2.name as group_name from api_config t1 join api_group t2 on t1.group_id = t2.id")
    List<ApiDto> getAllDetail();

    @Select("select id from api_config;")
    List<String> getAllIPIDs();

    @Select("select token from token where id = (select token_id from api_auth where group_id = #{groupId});")
    String getToken(String groupId);
}
